public class DistributeSurvey
{
   // public Account acc{get;set;}
    public List<SurveyEntry> accLeftList{get;set;}
    public List<SurveyEntry> accRightList{get;set;}
    public List<Account> allRightList{get;set;}  
    public List<Account> allLeftList{get;set;}   
    public List<MessageEntry> msgLeftList{get;set;}
    public List<MessageEntry> msgRightList{get;set;} 
    public String UserName{get;set;}
    public SurveyDistribution__c surveyDistribution{get;set;}
    public String Msg{get;set;} 
    public List<SelectOption> channelList{get;set;} 
    public List<SelectOption> outletTypeList{get;set;}
    public List<SelectOption> ChainCustomerList{get;set;}
    public String channelValue{get;set;}//渠道类型
    public String outletTypeValue{get;set;}//门店类型
    public Boolean isCheck{get;set;}
    public Boolean isCheck2{get;set;}  
    public Boolean isCheck3{get;set;}
    public Boolean SDisplay{get;set;}//是否显示Trade类型
    public Boolean MDisplay{get;set;}//是否显示medical类型
    public String errorMsg{get;set;}
    public List<SelectOption> RegionList{get;set;}
    public String RegionValue{get;set;}//大区的值
    public String SubRegionValue{get;set;}//片区的值
    public String AreaValue{get;set;}//区域的值
    public String CityValue{get;set;}//城市的值 
    public Boolean HaveTakePhoto{get;set;}//是否要拍照
    public List<SelectOption> MsgTypeList{get;set;}
    public String MsgTypeValue{get;set;}
    public String ChainCustomerValue{get;set;}//连锁客户
    public Boolean isNC{get;set;}
    //public List<SelectOption> FilterOptions{get;set;}//条件下拉列表，0、按全国，1、大区，2、条件
    //public String FilterValue{get;set;}
    public Boolean FilterIsDisplay{get;set;}//条件类开是否显示
    public List<SelectOption> RegionOptions{get;set;}//加载大区
    public Boolean RegionIsDisplay{get;set;}//按大区搜索是否显示
    //public Boolean FilterPanelIsDisplay{get;set;}//搜索条件是否显示
    public Integer Leftindex{get;set;}//标示左边分页的位置
    public Integer RightIndex{get;set;}//标志右边分页位置
    public Integer LeftCurrentIndex{get;set;}
    public Integer RightCurrentIndex{get;set;}
    public Integer LeftCheckCount{get;set;}
    public Integer RightCheckCount{get;set;}
    //计算左边的页总数
    public Integer LeftPageSum
    {
        get
        {
            if(allLeftList!=NULL)
            {
                //计算页总数
                String Sum=String.valueOf(allLeftList.size()/500);
                Integer Num=0;
                if(Math.mod(allLeftList.size(),500)>0)
                    Num=Integer.valueOf(Sum)+1;
                else
                    Num=Integer.valueOf(Sum);
                    
                return Num;
            }
            else
                return 0;
        }
    }
    //计算右边的页总数
    public Integer RightPageSum
    {
        get
        {
            if(accRightList!=NULL)
            {
                //计算页总数
                String Sum=String.valueOf(accRightList.size()/500);
                Integer Num=0;
                if(Math.mod(accRightList.size(),500)>0)
                    Num=Integer.valueOf(Sum)+1;
                else
                    Num=Integer.valueOf(Sum);
                    
                return Num;
            }
            else
                return 0;
        }
    }
    
    public String[] selectedRegion{get;set;}
    //public List<SelectOption> MedicalRegionList{get;set;}
    public String MedicalRegionValue{get;set;}
    
    
    public User CurrentUser
    {
        get
        {
            return [select Id,UserAreaValue__c,UserCity__c,UserSubRegion__c,UserRegion__c from User where Id=:UserInfo.getUserId()];
        }
    }
    
    public DistributeSurvey(ApexPages.StandardController controller)
    { 
    
        RegionIsDisplay=false;
         //设置发送的条件
        FilterIsDisplay=true;
        selectedRegion=new String[]{};
        
        Leftindex=0;
        RightIndex=0;
        LeftCurrentIndex=0;
        RightCurrentIndex=0;
        LeftCheckCount=0;
        RightCheckCount=0;
        RegionList=new List<SelectOption>();
        
         User u=[select FunctionDepartment__c from User where Id=:UserInfo.getUserId()];
        MsgTypeList=new List<SelectOption>();
        
        if(u.FunctionDepartment__c=='Trade Sales' || u.FunctionDepartment__c=='Trade Functional')
            MsgTypeList.add(new SelectOption('营业信息','营业信息'));
         else if(u.FunctionDepartment__c=='Medical Sales' || u.FunctionDepartment__c=='Medical Functional')
         {
           MsgTypeList.add(new SelectOption('医务信息','医务信息'));
           
         }
        else if(u.FunctionDepartment__c=='Trade&Medical Sales' || u.FunctionDepartment__c=='Trade&Medical Functional')
        {
            MsgTypeList.add(new SelectOption('营业信息','营业信息'));
            MsgTypeList.add(new SelectOption('医务信息','医务信息'));
        }
        
        if(u.FunctionDepartment__c=='Medical Sales' || u.FunctionDepartment__c=='Medical Functional')
        {
            SDisplay=false;
            MDisplay=true;
            FilterIsDisplay=false;
            //RegionIsDisplay=false;
        }
        msgLeftList=new List<MessageEntry>();
        msgRightList=new List<MessageEntry>();
        
        surveyDistribution=new SurveyDistribution__c();
        accLeftList=new List<SurveyEntry>();
        accRightList=new List<SurveyEntry>();
        allRightList=new List<Account>();
        
        Account testAcc=new Account(Name='test',OutletCode__c='test');
        allRightList.add(testAcc);
        
        channelList=new List<SelectOption>();
        Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.Channel__c;
        List<Schema.PicklistEntry> P = F.getPicklistValues();
       
        channelList.add(new SelectOption('0','ALL'));
        for(Schema.PicklistEntry entry : P)
        {
           channelList.add(new SelectOption(entry.getValue(),entry.getLabel()));
        }
        
        outletTypeList=new List<SelectOption>();
        Schema.DescribeFieldResult f2 = Schema.sObjectType.Account.fields.Outlet_Type__c;
        List<Schema.PicklistEntry> P2 = F2.getPicklistValues();
        outletTypeList.add(new SelectOption('0','ALL'));
        for(Schema.PicklistEntry entry : P2)
        {
           outletTypeList.add(new SelectOption(entry.getValue(),entry.getLabel()));
        }
        
        ChainCustomerList=new List<SelectOption>();
        Schema.DescribeFieldResult f3 = Schema.sObjectType.Account.fields.Chain_Customer__c;
        List<Schema.PicklistEntry> P3 = F3.getPicklistValues();
        ChainCustomerList.add(new SelectOption('0','ALL'));
        for(Schema.PicklistEntry entry : P3)
        {
           ChainCustomerList.add(new SelectOption(entry.getValue(),entry.getLabel()));
        }
        
       //加载trade大区
      // RegionList.add(new SelectOption('0','ALL'));
      if(CurrentUser.UserRegion__c==NULL)
      {
          for(Place__c p1:[select Id,Name from Place__c where PlaceType__c='Region'])
              RegionList.add(new SelectOption(p1.Name,p1.Name));
      }
      else
      {
        if(CurrentUser.UserRegion__c!=NULL && (CurrentUser.UserSubRegion__c==NULL && CurrentUser.UserAreaValue__c==NULL && CurrentUser.UserCity__c==NULL))
            RegionList.add(new SelectOption(CurrentUser.UserRegion__c,CurrentUser.UserRegion__c));
        else
            FilterIsDisplay=false;
      }
    }
    //加载medical大区
    public List<SelectOption> MedicalRegionList
    {
        get
        {
            if(MedicalRegionList==NULL)
                MedicalRegionList=new List<SelectOption>();
            else
                MedicalRegionList.clear();
                    
             MedicalRegionList.add(new SelectOption('0','所有大区'));
             if(CurrentUser.UserRegion__c==NULL)
             {
                for(Place__c p1:[select Id,Name from Place__c where PlaceType__c='Region'])
                    MedicalRegionList.add(new SelectOption(p1.Name,p1.Name));
             }
             else
             {
                MedicalRegionList.add(new SelectOption(CurrentUser.UserRegion__c,CurrentUser.UserRegion__c));
             }
            return MedicalRegionList;
        }
        set;
    }
    
     public List<SelectOption> SubRegionList
    {
        get
        {
            if(SubRegionList==null)
                SubRegionList=new List<SelectOption>();
            else
                SubRegionList.clear();
            SubRegionList.add(new SelectOption('0','所有片区'));    
              
            if(CurrentUser.UserSubRegion__c!=NULL)
            {
                SubRegionList.add(new SelectOption(CurrentUser.UserSubRegion__c,CurrentUser.UserSubRegion__c));
            }
            else
            {
                if(MedicalRegionValue!='' && MedicalRegionValue!=NULL)
                {
                    for(Place__c p:[select Id,Name from Place__c where PlaceType__c='Sub-region' and Region__r.Name=:MedicalRegionValue])
                    {
                    SubRegionList.add(new SelectOption(p.Name,P.Name));
                    } 
                }
                else
                {
                    if(CurrentUser.UserRegion__c==NULL)
                    {
                        for(Place__c p:[select Id,Name from Place__c where PlaceType__c='Sub-region'])
                        {
                            SubRegionList.add(new SelectOption(p.Name,P.Name));
                        } 
                    }
                    else
                    {
                         for(Place__c p:[select Id,Name from Place__c where PlaceType__c='Sub-region' and Region__r.Name=:CurrentUser.UserRegion__c])
                        {
                            SubRegionList.add(new SelectOption(p.Name,P.Name));
                        } 
                    }
                }
            }
            
            return SubRegionList;
        }
        set;    
    }
    
    public List<SelectOption> AreaList
    {
        get
        {
            if(AreaList==null)
                AreaList=new List<SelectOption>();
            else
                AreaList.clear();
                
            AreaList.add(new SelectOption('0','所有区域'));
            if(CurrentUser.UserAreaValue__c==NULL)
            {
                for(Place__c p:[select Id,Name from Place__c where PlaceType__c='Area' and Subregion__r.Name=:SubRegionValue])
                {
                    AreaList.add(new SelectOption(p.Name,P.Name));
                }
            }
            else
            {
                List<String> arr=String.valueOf(CurrentUser.UserAreaValue__c).split(';');
                if(arr!=NULL || arr.size()>0)
                {
                    for(String s:arr)
                        AreaList.add(new SelectOption(s,s));
                }
            }
            return  AreaList;
        }
        set;
    }
    
    public List<SelectOption> CityList
    {
        get
        {
            if(CityList==null)
                CityList=new List<SelectOption>();
            else
                CityList.clear();
           
           CityList.add(new SelectOption('0','所有城市'));
           if(CurrentUser.UserCity__c==NULL)
           {
                for(Place__c p:[select Id,Name from Place__c where PlaceType__c='City' and Area__r.Name=:AreaValue])
                {
                    CityList.add(new SelectOption(P.Name,P.Name));
                }   
           }
           else
           {
                List<String> arr=String.valueOf(CurrentUser.UserCity__c).split(';');
                if(arr!=NULL || arr.size()>0)
                {
                    for(String s:arr)
                        CityList.add(new SelectOption(s,s));
                }
           }
            return CityList;
        }
        set;
    }
    
     public String GetTradeCityFilter()
    {
        //User u=[select UserRegion__c,UserSubRegion__c,UserAreaValue__c,UserCity__c from User where Id=:UserInfo.getUserId()];
        String Str='';
       
        if(SubRegionValue != '0')
        {
            if(Str!='')
                str+=' and ';
            str+=' OutletSubRegion__c=\''+SubRegionValue+'\'';
        }
         else
        {
            if(CurrentUser.UserSubRegion__c!=NULL)
            {
                if(Str!='')
                    str+=' and ';
                str+=' OutletSubRegion__c=\''+CurrentUser.UserSubRegion__c+'\'';
            }
        }
       
        if(AreaValue != '0')
        {
            if(Str!='')
                str+=' and ';
            str+=' OutletArea__c=\''+AreaValue+'\'';
        }
         else
        {
            if(CurrentUser.UserAreaValue__c!=NULL)
            {
                List<String> arr=String.valueOf(CurrentUser.UserAreaValue__c).split(';');
                if(arr!=NULL || arr.size()>0)
                {
                    if(Str!='')
                        str+=' and ';
                    String f=''; 
                    
                    for(String s:arr)
                    {
                        if(f!='')
                            f+=' or';
                            
                        f+=' OutletArea__c=\''+s+'\'';
                    }
                    
                    Str+=' ('+f+')';
                }
            }
        }
       
        if(CityValue != '0')
        {
            if(Str!='')
                str+=' and ';
            str+=' City__r.Name=\''+CityValue+'\'';
        }
        else
        {
            if(CurrentUser.UserCity__c!=NULL)
            {
                List<String> arr=String.valueOf(CurrentUser.UserCity__c).split(';');
                if(arr!=NULL || arr.size()>0)
                {
                    if(Str!='')
                        str+=' and ';
                    String f=''; 
                    
                    for(String s:arr)
                    {
                        if(f!='')
                            f+=' or';
                            
                        f+=' City__r.Name=\''+s+'\'';
                    }
                    
                    Str+=' ('+f+')';
                }
            }
        }
        
        return Str;
    }
    
    public List<Account> SearchData()
    {
       
        String sql='select Id,Name from account ';
        String filter='';
        if(channelValue != NULL && channelValue!='0')
            filter+='Channel__c=\''+channelValue+'\'';
        if(outletTypeValue != NULL && outletTypeValue!='0')
        {
            if(filter.length()>0)
                filter+=' and ';
                
            filter+=' Outlet_Type__c=\''+outletTypeValue+'\'';
        }
        
        if(ChainCustomerValue != NULL && ChainCustomerValue!='0')
        {
            if(filter.length()>0)
                filter+=' and ';
                
            filter+=' Chain_Customer__c=\''+ChainCustomerValue+'\'';
        }
        
        if(isNC != NULL && isNC==true)
        {
            if(filter.length()>0)
                filter+=' and ';
                
            filter+=' With_NC_or_not__c='+isNC+'';
        }
        
         String city=GetTradeCityFilter();
        if(city !='' || city.length()>0)
        {
            if(filter.length()>0)
                filter+=' and ';
                
            filter+=' ('+city+')';
        }   
      
           if((filter=='' || filter.length()==0) && (city==null || city.length()==0))
            {
                    throw new CustomException ('请选择一个条件再进行搜索' ); 
            }
              
         if(filter.length()>0)
                filter+=' and ';
         
        filter+=' Active_Status__c=\'正常营业\'';
        
        if(filter.length()>0)
            sql+=' where '+filter;
            
         sql+=' order by name limit 8000';  //分页控制
          
       List<Account> accList= DataBase.query(sql); 
       return accList;
    }
    public PageReference LeftNext()
    {
       // if(LeftCurrentIndex<=LeftPageSum)
       // {
            
            if(LeftCheckCount==500)//判断选中的条数是否大于等于500，如果是则LeftCurrentIndex归零，页码减1
            {
                LeftCheckCount=0;
            }
            else 
            {
                LeftCurrentIndex=LeftCurrentIndex+1;//页码加1 
                LeftCheckCount=0;
            }
            
            isCheck=false;
            //LeftCurrentIndex=LeftCurrentIndex+1;
            Integer CurruntNum=LeftCurrentIndex*500;
            accLeftList.clear();
            
            for(Integer i=CurruntNum-500+1;i<=CurruntNum;i++)
            {
                if(i<allLeftList.size() && allLeftList[i]!=NULL)
                {
                    if(allLeftList[i].Name!='test')
                        accLeftList.add(new SurveyEntry(false,allLeftList[i]));
                }
            }
       // }
        //}
        return null;
    }
    public PageReference LeftPrevious()
    {
        if(LeftCurrentIndex>1)
       // if(LeftCurrentIndex>1)
        {
            LeftCurrentIndex=LeftCurrentIndex-1;//页码减1 
            isCheck2=false;
            Integer CurruntNum=LeftCurrentIndex*500;
            accLeftList.clear();
            for(Integer i=CurruntNum-500+1;i<=CurruntNum;i++)
            {
                if(i<allLeftList.size() && allLeftList[i]!=NULL)
                {
                    if(allLeftList[i].Name!='test')
                       accLeftList.add(new SurveyEntry(false,allLeftList[i]));
                }
            }
        }
        return null;
    }
    
     public PageReference RightNext()
    {
        //RightPageSum  
       // if(RightCurrentIndex<=RightPageSum)
        //if(RightCurrentIndex<2)
      //  {
            isCheck2=false;
            
            if(RightCheckCount==500)//判断选中的条数是否大于等于500，如果是则LeftCurrentIndex归零，页码减1
            {
                RightCheckCount=0;
            }
            else 
            {
                RightCurrentIndex=RightCurrentIndex+1;//页码加1 
                RightCheckCount=0;
            }
            
           // RightCurrentIndex=RightCurrentIndex+1;
            Integer CurruntNum=RightCurrentIndex*500;
            accRightList.clear();
            
            for(Integer i=CurruntNum-500+1;i<=CurruntNum;i++)
            {
                if(i<allRightList.size() && allRightList[i]!=NULL)
                {
                    if(allRightList[i].Name!='test')
                        accRightList.add(new SurveyEntry(false,allRightList[i]));
                }
            }
      //  }
        
        return null;
    }
    public PageReference RightPrevious()
    {
        //if(RightCurrentIndex>1 && RightCurrentIndex<RightPageSum)
        if(RightCurrentIndex>1 )
        {
            RightCurrentIndex=RightCurrentIndex-1;//页码减1 
            isCheck2=false;
            Integer CurruntNum=RightCurrentIndex*500;
            accRightList.clear();
            for(Integer i=CurruntNum-500+1;i<=CurruntNum;i++)
            {
                if(i<allRightList.size() && allRightList[i]!=NULL)
                {
                    if(allRightList[i].Name!='test')
                       accRightList.add(new SurveyEntry(false,allRightList[i]));
                }
            }
        }
      
        return null;
    } 
    
    public PageReference Searchs()
    {
        
        Leftindex=0;
        LeftCheckCount=0;
        RightCheckCount=0;
        
        if(allLeftList!=NULL)
            allLeftList.clear();
         else
            allLeftList=new List<Account>();
            
        if(accLeftList!=NULL)
            accLeftList.clear();
        
        Map<Id,Account> mapSearchData=new Map<Id,Account>();
        try
        {
                 mapSearchData=new Map<Id,Account>(SearchData());
        }
         catch(Exception ex)
        {
              ApexPages.addMessages(ex);
               return null;
        }
        //剔除重复的
       
        for(Account acc:allRightList)
        {
            if(acc.id!=NULL)
            {
                if(mapSearchData.containsKey(acc.id))
                {
                    mapSearchData.remove(acc.id);
                }
            }
        }
        
        for(Account acc:mapSearchData.values())
        {
            if(allLeftList.size()==0)
            {
                Account testAcc=new Account(Name='test',OutletCode__c='test');
               SurveyEntry entry=new SurveyEntry(false,testAcc);
                allLeftList.add(testAcc);
            }
            allLeftList.add(acc);
        }
        //allLeftList=SearchData();
       
        for(Integer i=1;i<=500;i++)
        {
            if(allLeftList.size()>i && i>=0)
            {
                if(allLeftList[i].Name!='test')
                    accLeftList.add(new SurveyEntry(false,allLeftList[i]));
            }
        }
        if(allLeftList.size()>0)
            LeftCurrentIndex=1;//页码加1 
            
      // System.debug('*********************总数:'+allLeftList.size());
        return null;
    }
   
    public PageReference Searchs2()
    {
        errorMsg='';
        accLeftList.clear();
        String sql='select Id,Name from User where name like \'%'+UserName+'%\'';
        
       sql+=' and IsActive=true and FunctionDepartment__c like \'%Medical%\'';
        if(GetFilter() !='' || GetFilter().length()>0)
            sql+=' and ('+GetFilter()+')';
       
       String city=GetMedicalCityFilter();
       if(city !='' || city.length()>0)
            sql+=' and ('+city+')';
       
       msgLeftList.clear();
        for(User u:DataBase.query(sql))
        {
            MessageEntry entry=new MessageEntry(false,u);
            msgLeftList.add(entry);
        }
        
         for(Integer i=0;i<msgRightList.size();i++)
        {
            MessageEntry en=msgRightList[i];
            User u=en.u;
            for(Integer j=0;j<msgLeftList.size();j++)
            {
                MessageEntry en2=msgLeftList[j];
                if(en.u.Id==en2.u.Id)
                {
                    msgLeftList.remove(j);
                }
            }
        }
       // errorMsg=sql;
        return null;
    }
    
    
    public String GetMedicalCityFilter()
    {
       // User u=[select UserRegion__c,UserSubRegion__c,UserAreaValue__c,UserCity__c from User where Id=:UserInfo.getUserId()];
        
        String Str='';
        if(MedicalRegionValue != '0')
        {
            str+=' UserRegion__c=\''+MedicalRegionValue+'\'';
        }
        else
        {
            if(CurrentUser.UserRegion__c!=NULL)
                str+=' UserRegion__c=\''+CurrentUser.UserRegion__c+'\'';
        }
        if(SubRegionValue != '0')
        {
            if(Str!='')
                str+=' and ';
            str+=' UserSubRegion__c=\''+SubRegionValue+'\'';
        }
        else
        {
            if(CurrentUser.UserSubRegion__c!=NULL)
            {
                if(Str!='')
                    str+=' and ';
                
                str+=' UserSubRegion__c=\''+CurrentUser.UserSubRegion__c+'\'';
            }
        }
        
        if(AreaValue != '0')
        {
            if(Str!='')
                str+=' and ';
            str+=' UserAreaValue__c includes(\''+AreaValue+'\')';
        }
       else
        {
           /*  if(CurrentUser.UserAreaValue__c!=NULL)
            {
                if(Str!='')
                    str+=' and ';
                str+=' UserAreaValue__c includes(\''+CurrentUser.UserAreaValue__c+'\')';
            }*/
            
             if(CurrentUser.UserAreaValue__c!=NULL)
            {
                List<String> arr=String.valueOf(CurrentUser.UserAreaValue__c).split(';');
                if(arr!=NULL || arr.size()>0)
                {
                    if(Str!='')
                        str+=' and ';
                    String f=''; 
                    
                    for(String s:arr)
                    {
                        if(f!='')
                            f+=' or';
                            
                        f+=' UserAreaValue__c includes(\''+s+'\')';
                    }
                    
                    Str+=' ('+f+')';
                }
            }
        }
        if(CityValue != '0')
        {
            if(Str!='')
                str+=' and ';
            str+=' UserCity__c includes(\''+CityValue+'\')';
        }
        else
        {
            if(CurrentUser.UserCity__c!=NULL)
            {
                List<String> arr=String.valueOf(CurrentUser.UserCity__c).split(';');
                if(arr!=NULL || arr.size()>0)
                {
                    if(Str!='')
                        str+=' and ';
                    String f=''; 
                    
                    for(String s:arr)
                    {
                        if(f!='')
                            f+=' or';
                            
                        f+=' UserCity__c includes(\''+s+'\')';
                    }
                    
                    Str+=' ('+f+')';
                }
            }
        }
        return Str;
    }
    
     public String GetFilter()
    {
        String filter='';
        User u=[select Id,Name,Title__c,FunctionDepartment__c from User where Id=:UserInfo.getUserId()];
       if(u.Title__c=='Area/District Sales Manager')
       {
         for(User u1:[select Id,Name,Title__c from User where ManagerId=:u.Id])
         {
            if(u1.Title__c!='Sales Rep')
            {
                for(User u2:[select Id,Name,Title__c from User where ManagerId=:u1.Id])
                {
                    
                    if(u2.Title__c=='Sales Rep')
                    {
                        if(filter.length()>0)
                            filter+=' or';
                            
                        filter+=' Id=\''+u2.Id+'\' ';
                    }
                        
                }
            }
            if(u1.Title__c=='Sales Rep')
            {
                if(filter.length()>0)
                    filter+=' or';
                    
                filter+=' Id=\''+u1.Id+'\' ';
            }
         }
       }
       else if(u.Title__c=='Sales Supervisor')
       {
            for(User u2:[select Id,Name,Title__c from User where ManagerId=:u.Id])
            {
                    if(u2.Title__c =='Sales Rep')
                    {
                        if(filter.length()>0)
                            filter+=' or';
                            
                        filter+=' Id=\''+u2.Id+'\' ';
                    }
            }
       }
       
       return filter;
    }
    
    
     public PageReference onChangeSelectAll()
    {
        for(SurveyEntry en:accLeftList)
        {
            en.IsCheck=isCheck;
        }
        
        return null;
    }
     public PageReference onChangeSelectAllOutlet()
    {
        for(SurveyEntry en:accRightList)
        {
            en.IsCheck=isCheck2;
        }
        
        return null;
    }
    
     public PageReference onChangeSelectAll2()
    {
        for(MessageEntry en:msgLeftList)
        {
            en.Ischeck=isCheck;
        }
        return null;
    }
     public PageReference onChangeSelectAllUser()
    {
        for(MessageEntry en:msgRightList)
        {
            en.Ischeck=isCheck3;
        }
        
        return null;
    }
    public PageReference Add()
    {
        isCheck=false;
        Set<Id> DelList=new Set<Id>();
        for(Integer i=0;i<accLeftList.size();i++)
        {
            SurveyEntry e=accLeftList[i];
            if(e.Ischeck)
            {
                e.IsCheck=false;
                allRightList.add(e.acc);
                if(accRightList.size()<500)//每次显示500条数据
                {
                    accRightList.add(e);
                }
                LeftCheckCount=LeftCheckCount+1;
                accLeftList.remove(i);
                DelList.add(e.acc.Id);//加到map里面删除大的左边的集合
                i=i-1;
                
                
            }
        }
        if(accRightList.size()<=500)
            RightCurrentIndex=1;
            
        if(DelList.size()>0)
            DeleteLeftAllList(DelList);//删除右边的大集合
            
       //errorMsg=String.valueOf(allLeftList.size());     
        return null;
    }
    
    public PageReference AddMedical()
    {
        for(Integer i=0;i<msgLeftList.size();i++)
        {
            MessageEntry e=msgLeftList[i];
            if(e.Ischeck)
            {
                e.Ischeck=false;
                msgRightList.add(e);
                msgLeftList.remove(i);
                i=i-1;
            }
        }
          isCheck=false;
      //  isCheck3=false;
        
        return null;
    }
    
    public PageReference Del()//从右边添加到左边
    {
        isCheck2=false;
        Set<Id> DelList=new Set<Id>();
        for(Integer i=0;i<accRightList.size();i++)
        {
            SurveyEntry e=accRightList[i];
            if(e.Ischeck)
            {
                e.Ischeck=false;
                //添加到左边大集合
                if(accLeftList.size()<500)
                    accLeftList.add(e);//添加到左边小集合
                allLeftList.add(e.acc);//添加到大的左边集合  
                accRightList.remove(i);//删除右边小集合
                DelList.add(e.acc.Id);//加到map里面删除大的右边的集合
              //  allRightList.remove(i);
              
              RightCheckCount=RightCheckCount+1;
                i=i-1;
            }
        }
        if(DelList.size()>0)
            DeleteRightAllList(DelList);//删除右边的大集合
        return null;
    }
    
     public PageReference DelMedical()
    {
        for(Integer i=0;i<msgRightList.size();i++)
        {
            MessageEntry e=msgRightList[i];
            if(e.Ischeck)
            {
                e.Ischeck=false;
                msgLeftList.add(e);
                msgRightList.remove(i);
                i=i-1;
            }
        }
        isCheck3=false;
        return null;
    }
    //删除右边的大集合
    public void DeleteRightAllList(Set<Id> DelList)
    {
        for(Integer i=0;i<allRightList.size();i++)
        {
            Account acc=allRightList[i];
            if(DelList.contains(acc.Id))
            {
                allRightList.remove(i);
                i=i-1;
            }
        }
    }
    //删除左边大集合
     public void DeleteLeftAllList(Set<Id> DelList)
    {
        for(Integer i=0;i<allLeftList.size();i++)
        {
            Account acc=allLeftList[i];
            if(DelList.contains(acc.Id))
            {
                allLeftList.remove(i);
                i=i-1;
            }
        }
    }
    public PageReference OnchageAction()
    {
        if(MsgTypeValue=='医务信息')
        {
           //SDisplay=false;
           MDisplay=true;
           //FilterPanelIsDisplay=false;
           FilterIsDisplay=false;
           RegionIsDisplay=false;
           
           
        }
        else if(MsgTypeValue=='营业信息')
        {
           //SDisplay=false;
           MDisplay=false;
           //RegionIsDisplay=false;
          // FilterValue='0';
           FilterIsDisplay=true;
        }
        MedicalRegionValue='0';
        SubRegionValue='0';
        AreaValue='0';
        CityValue='0';
       // FilterValue='2';
        CityList.clear();
        msgLeftList.clear();
        msgRightList.clear();
        accLeftList.clear();
        accRightList.clear();
        if(allLeftList!=NULL)
            allLeftList.clear();
            
        if(allRightList!=NULL)
            allRightList.clear();
        errorMsg='';
        return null;
    } 
    public PageReference Save()
    {
        if(surveyDistribution.EndDate__c<surveyDistribution.StartDate__c)
        {
            Msg='结束时间不能小于开始时间';
            return null;
        }
        else
        {
            if(MsgTypeValue=='营业信息')
            {
                if(allRightList.size()>0 || selectedRegion!=NULL)
                {
                    surveyDistribution.SurveyDistributionType__c=MsgTypeValue;
                    insert surveyDistribution;
                }
                 else
                {
                    errorMsg='请选择要发送的门店';
                    return null;
                }
                    
                  if(!RegionIsDisplay)//按条件发送
                  {
                       List<TIMBASURVEYS__Recipient__c> listMsg=new List<TIMBASURVEYS__Recipient__c>();
                       Set<Id> idList=new Set<Id>();
                        for(Account e:allRightList)
                        {   
                            if(e.id!=NULL && e.Name!='test')
                            {
                                if(!idList.contains(e.Id))
                                {
                                    TIMBASURVEYS__Recipient__c msg=new TIMBASURVEYS__Recipient__c();
                                    msg.Outlet__c=e.Id;
                                    msg.TIMBASURVEYS__isAnonymous__c=false;
                                    msg.TakePhoto__c=HaveTakePhoto;
                                    msg.Survey_Distribution__c=surveyDistribution.Id;
                                    msg.TIMBASURVEYS__Survey__c=surveyDistribution.Survey__c;
                                    msg.TIMBASURVEYS__Summary_Created__c=false;
                                    msg.TIMBASURVEYS__IsPortalUser__c=false;//dd
                                    listMsg.add(msg);
                                    idList.add(e.Id);
                                }
                            }
                        }
                        insert listMsg;
                  }
                  else//按大区发送
                  {
                    String strFilter='';
                    BatchDistributeOutlet batch=new BatchDistributeOutlet();
                    for(Integer i=0;i<selectedRegion.size();i++)
                    {
                        
                        if(strFilter!='')
                            strFilter+=',\''+selectedRegion[i]+'\''; 
                        else
                            strFilter+='\''+selectedRegion[i]+'\''; 
                    }
                    batch.stringSql='select Id from Account where OutletRegion__c in ('+strFilter+')';
                    batch.DistributeId=surveyDistribution.Id;
                    batch.hasPhote=HaveTakePhoto;
                    batch.SurveyId=surveyDistribution.Survey__c; 
                    Database.executeBatch(batch);
                    errorMsg='select Id from Account where OutletRegion__c in ('+strFilter+')';
                  }     
               } 
            }
            if(MsgTypeValue=='医务信息')
            {
                 //insert Message History Record
                List<TIMBASURVEYS__Recipient__c> listMsg=new List<TIMBASURVEYS__Recipient__c>();
               // List<TIMBASURVEYS__Recipient__c> updateMsg=new List<TIMBASURVEYS__Recipient__c>();
                //String str='';
                for(MessageEntry e:msgRightList)
                {   
                    TIMBASURVEYS__Recipient__c msg=new TIMBASURVEYS__Recipient__c();
                   // msg.Outlet__c=e.acc.Id;
                    msg.TIMBASURVEYS__isAnonymous__c=false;
                    msg.TIMBASURVEYS__RelatedUser__c=e.u.Id;
                    msg.TakePhoto__c=HaveTakePhoto;
                    //msg.Survey_Distribution__c=surveyDistribution.Id;
                    msg.TIMBASURVEYS__Survey__c=surveyDistribution.Survey__c;
                    msg.TIMBASURVEYS__Summary_Created__c=false;
                    msg.TIMBASURVEYS__IsPortalUser__c=false;//dd
                    listMsg.add(msg);
                }
                //mhr.Receiver_List__c=str;
                //surveyDistribution.Channel__c=channelValue;
                //surveyDistribution.OutletType__c=outletTypeValue;
                surveyDistribution.SurveyDistributionType__c=MsgTypeValue;
                 if(listMsg.size()>0)
                {
                    insert surveyDistribution;
                    
                    for(TIMBASURVEYS__Recipient__c tr:listMsg)
                    {
                        tr.Survey_Distribution__c=surveyDistribution.Id;
                    }
                    insert listMsg;
                }
                else
                {
                    errorMsg='请选择要发送的用户';
                    return null;
                }
            }
            
            
            PageReference pr=new PageReference('/'+surveyDistribution.Id);
            pr.setRedirect(true);
            return pr;
        //return null;
    }
    public PageReference Cancel()
    {
        
       return null;
    }
    
    static testmethod void Test()
    {
        Place__c regs=new Place__c(PlaceType__c='Region',Name='华南区');
        insert regs;
        Place__c subregs=new Place__c(PlaceType__c='Sub-region',Name='华南一区',Region__c=regs.Id);
        insert subregs;
        Place__c areas=new Place__c(PlaceType__c='PlaceType__c',Name='广州区域',Region__c=regs.Id,Subregion__c=subregs.Id);
        insert areas;
        Place__c citys=new Place__c(PlaceType__c='City',Name='广州',Region__c=regs.Id,Subregion__c=subregs.Id,Area__c=areas.Id);
        insert citys;
            
        Profile p = [select id from profile where name='System Administrator' or name = '系统管理员'  limit 1];
        User u = new User(alias = 'standtss', email='standarduser@testorgss.com',
        emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',Title__c='Area/District Sales Manager',
        localesidkey='en_US', profileid = p.Id,UserCity__c='广州',IsActive=true,
        UserAreaValue__c='广州区域',UserSubRegion__c='华南一区',UserRegion__c='华南区',
        timezonesidkey='America/Los_Angeles', username='standardusers@testorg.com');
        insert u;
        
        User test = new User(alias = 'standtss', email='str@testorgss.com',Title__c='Sales Rep',ManagerId=u.Id,
        emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
        localesidkey='en_US', profileid = p.Id,UserCity__c='广州',FunctionDepartment__c='Medical Sales',
        UserAreaValue__c='广州区域',UserSubRegion__c='华南一区',UserRegion__c='华南区',IsActive=true,
        timezonesidkey='America/Los_Angeles', username='strs@testorg.com');
        insert test;
        
         Account acc=new Account();
         acc.Name='test';
         acc.Channel__c='特大型综合超市';
         acc.Outlet_Type__c='全国重点客户';
         acc.Contact__c='aaa';
         acc.No_of_checkout__c=22;
         acc.ContactPhoneNumber__c='1234567456';
         acc.City__c=citys.Id;
         acc.OwnerId=u.Id;
         insert acc;
        
        System.runAs(u)
        {
          /*  SurveyDistribution__c sd=new SurveyDistribution__c();
            //Message__c m=new Message__c();
            ApexPages.StandardController sc = new ApexPages.StandardController(sd);
            DistributeSurvey send=new DistributeSurvey(sc);
            //SendMessage send=new SendMessage(sc);
            send.surveyDistribution.SurveyDistributionType__c='营业信息';
            send.OnchageAction();
            //send.SubRegionList=null;
           // send.AreaList=null;
            send.RegionValue='华南区';
            send.SubRegionValue='华南一区';
            send.AreaValue='广州区域';
            send.channelValue='特大型综合超市';
            send.outletTypeValue='全国重点客户';
            List<SelectOption> subss=send.SubRegionList;
            List<SelectOption> awrea=send.AreaList;
            List<SelectOption> cwity=send.CityList;
//            send.accRightList.add(new SurveyEntry(false,acc));
            send.Searchs();
          //  send.onChangeSelectAll();
            send.Add();
            send.Del();
           // send.surveyDistribution.Name='test';
            //send.surveyDistribution.Content__c='test';
            send.surveyDistribution.StartDate__c=Date.today();
            send.surveyDistribution.EndDate__c=Date.today();
            
            //send.Searchs();
            send.MsgTypeValue='营业信息';
            send.HaveTakePhoto=false;
            send.Save();
            send.Cancel();*/
        }
        
        User u2 = new User(alias='standtss', email='standaerduser@testorgss.com',
        emailencodingkey='UTF-8', lastname='Testeing', languagelocalekey='en_US',
        localesidkey='en_US', profileid = p.Id,FunctionDepartment__c='Medical Sales',IsActive=true,
        timezonesidkey='America/Los_Angeles', username='staendardusers@testorg.com');
        insert u2;
        System.runAs(u2)
        {
            SurveyDistribution__c sd=new SurveyDistribution__c();
            //Message__c m=new Message__c();
            ApexPages.StandardController sc = new ApexPages.StandardController(sd);
            DistributeSurvey send=new DistributeSurvey(sc);
            
            List<SelectOption> t=new List<SelectOption>();
            t.add(new SelectOption('华南区','华南区'));
            send.SubRegionList=t;
            
             List<SelectOption> t2=new List<SelectOption>();
            t2.add(new SelectOption('广州区域','广州区域'));
            send.AreaList=t2; 
            
            send.surveyDistribution.SurveyDistributionType__c='医务信息';
            send.OnchageAction();
           // send.user.Username='luo'; 
            send.RegionValue='华南区';
            send.SubRegionValue='华南一区';
            send.AreaValue='广州区域';
            List<SelectOption> sub=send.SubRegionList;
            List<SelectOption> area=send.AreaList;
            List<SelectOption> city=send.CityList;
//            send.accRightList.add(new SurveyEntry(true,acc));
            send.onChangeSelectAll();
            send.Searchs2();
            
            send.surveyDistribution.StartDate__c=Date.today();
            send.surveyDistribution.EndDate__c=Date.today();
            //send.Searchs();
            send.MsgTypeValue='医务信息';
            send.HaveTakePhoto=false;
            send.onChangeSelectAllUser();
            send.msgRightList.add(new MessageEntry(true,test));
            send.Save();
        }
        
        
        User u3 = new User(alias='standtss', email='aerduser@testorgss.com',
        emailencodingkey='UTF-8', lastname='Testeing', languagelocalekey='en_US',
        localesidkey='en_US', profileid = p.Id,FunctionDepartment__c='Trade Sales',IsActive=true,
        timezonesidkey='America/Los_Angeles', username='rdusers@testorg.com',
        UserCity__c='广州',
        UserAreaValue__c='广州区域',UserSubRegion__c='华南一区',UserRegion__c='华南区'
        );
        insert u3;
        System.runAs(u3)
        {
            SurveyDistribution__c sd=new SurveyDistribution__c();
            //Message__c m=new Message__c();
            ApexPages.StandardController sc = new ApexPages.StandardController(sd);
            DistributeSurvey send=new DistributeSurvey(sc);
            
             List<SelectOption> t=new List<SelectOption>();
            t.add(new SelectOption('华南一区','华南一区'));
            send.SubRegionList=t; 
            
            List<SelectOption> t2=new List<SelectOption>();
            t2.add(new SelectOption('广州区域','广州区域'));
            send.AreaList=t2;
            
            
            send.surveyDistribution.SurveyDistributionType__c='营业信息';
            send.OnchageAction();
            send.Searchs();
            send.onChangeSelectAllOutlet();
            MessageEntry en=new MessageEntry(true,u2);
            MessageEntry en2=new MessageEntry(true,u3);
            MessageEntry en3=new MessageEntry(true,test);
            send.msgLeftList.add(new MessageEntry(true,u2));
            send.msgLeftList.add(en2);
            send.AddMedical();
            send.msgLeftList.add(en);
            send.msgLeftList.add(en2);
            send.msgRightList.add(new MessageEntry(false,test));
            send.msgRightList.add(en);
            send.DelMedical();
            send.onChangeSelectAll2();
            
            //send.onChangeSelectAllRight();
        }
       
    }
}